﻿using System.IO;
using System.Runtime.InteropServices;
using SharpYaml.Serialization;

namespace AIClient.Configs
{
    public static class ConfigManager
    {
        public static CardCfgs           CardCfgs           { get; private set; }
        public static CardBattleFieldCfg CardBattleFieldCfg { get; private set; }
        public static ServerCfg          ServerCfg          { get; private set; }

        public static void Initialize(string path)
        {
            var serializer = new Serializer();
            serializer.Settings.EmitShortTypeName = true;
            ServerCfg          = Deserialize<ServerCfg>();
            CardCfgs           = Deserialize<CardCfgs>();
            CardBattleFieldCfg = Deserialize<CardBattleFieldCfg>();

            // DotNet Core的Tcp在Linux下时如果使用域名连接并KeepAlive则会出现异常报错
            // 目前暂时将域名直接转换成IP
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var splits = ServerCfg.ServerNode.Split("@");
                var ip = System.Net.Dns.GetHostAddresses(splits[1]);
                ServerCfg.ServerNode = $"{splits[0]}@{ip[0]}";
            }
                
            T Deserialize<T>()
            {
                return serializer.Deserialize<T>(File.ReadAllText(Path.Combine(path, $"{typeof(T).Name}.yaml")));
            }
        }
    }
}